package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.TreeProblem;

/**
 * https://leetcode.com/problems/binary-tree-maximum-path-sum/
 *
 * @author tzp
 * @since 2020/10/13
 */
public class LC124 implements TreeProblem {
    int max = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        if (root == null) return 0;
        rec(root);
        return max;
    }

    //当前root子树的最大单边sum
    public int rec(TreeNode root) {
        int leftMax = 0, rightMax = 0;
        if (root.left != null) {
            leftMax = rec(root.left);
        }
        if (root.right != null) {
            rightMax = rec(root.right);
        }
        int curSingleMax = root.val;
        curSingleMax = Math.max(curSingleMax, root.val + leftMax);
        curSingleMax = Math.max(curSingleMax, root.val + rightMax);

        max = Math.max(max, curSingleMax);
        max = Math.max(max, root.val + leftMax + rightMax);
        return curSingleMax;
    }

    public static void main(String[] args) {
//        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
        Integer[] a = {-10, 9, 20, null, null, 15, 7};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        System.out.println(new LC124().maxPathSum(treeNode));
    }
}
